from .InfluxdbHandler import InfluxdbHandler
from util.BasicAuth import BasicAuth
from util.PyMysql import PyMysql
import json
import time
from datetime import datetime
import requests
from util.time_transform import unix2str
from util.time_transform import str2unix
from influxdb import InfluxDBClient
from tornado import gen

class KeysHandler(InfluxdbHandler):
    @BasicAuth
    @gen.coroutine
    def get(self):
        clientid = self.get_argument('client', None)
        start_date = self.get_argument('create1', None)
        end_date = self.get_argument('create2', None)
        message_type = self.get_argument('message_type', None)
        fidis_name = self.get_argument('fidis_name', None)
        keys = self.get_argument("keys", "*")
        unix_start, unix_end = self.verify_date(start_date, end_date, 1, 1)
        limit = self.get_argument('limit', 50)
        page = self.get_argument('page_index', 1)
        try:
            offset = (int(page) - 1) * int(limit)
        except Exception as e:
            dt = {
                "success": False,
                "error": 'invalid page_index or limit'
            }
            self.write(dt)
            self.set_status(400)
            return
        if int(page) < 1:
            dt = {
                "success":False,
                "error": 'page_index must >0 '
            }
            self.write(dt)
            self.set_status(400)
            return
        fidis_name, ip = self.get_fidis_ip(fidis_name, clientid)
        influxdb_client = InfluxDBClient(ip, 8086)

        if message_type:
            topic_str = " and topic = '{}' ".format(message_type)
        else:
            topic_str = " "
        if start_date and end_date:
            limit_str = "time > {} and time < {} {} order by time".format(unix_start, unix_end, topic_str)
        elif start_date:
            limit_str = "time > {} {} order by time".format(unix_start, topic_str)
        elif end_date:
            limit_str = "time < {}  {} order by time desc".format(unix_end, topic_str)
        else:
            limit_str = "time < {} {} order by time desc".format(str2unix(None), topic_str)



        # sql = "select time, payload, topic from \"{}\" where {} limit {} offset {}".format(clientid, limit_str, limit, offset)
        sql = "select time, {}, topic  from \"{}\" where {} limit {} offset {}".format(keys, clientid, limit_str, limit,
                                                                                            offset)

        sql2 = "select count(*) from \"{}\" where {}".format(clientid, limit_str)
        result_data = influxdb_client.query(sql, epoch='s', database=fidis_name)
        my_list = []
        dt = {}
        for point in result_data:
            for data_dict in point:
                data_dict['time'] = unix2str(data_dict['time'])

                my_list.append(data_dict)

        dt["data"] = my_list
        dt["success"] = True
        self.write(json.dumps(dt))